package com.tale.ssm.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.util.StringUtil;
import com.tale.ssm.entity.Grade;
import com.tale.ssm.service.GradeService;
import com.tale.ssm.vo.Page;

@Controller
@RequestMapping("/grade")
public class GradeController {
	
	@Autowired
	private GradeService service;
	

	@GetMapping(value = "/list")
	public ModelAndView list(ModelAndView model) {
		model.setViewName("grade/grade_list");
		
		return model;
	}
	
	@PostMapping("/edit")
	@ResponseBody
	public Map<String, String> edit(Grade grade){
		Map<String, String> map = new HashMap<String, String>();
		map.put("type", "error");
		
		if(service.edit(grade) <= 0) {
			map.put("msg", "修改失败");
			return map;
		}
		
		map.put("type", "success");
		map.put("msg", "修改成功");
		
		return map;
	}
	
	@PostMapping("/delete")
	@ResponseBody
	public Map<String, String> delete(
			@RequestParam(value = "ids[]")Long[] ids
			){
		Map<String, String> map = new HashMap<String, String>();
		String id = "";
		for(Long i:ids) {
			id += i + ","; 
		}
		id = id.substring(0, id.length() - 1);
		if(service.delete(id) <= 0) {
			map.put("type", "error");
			map.put("msg", "删除失败");
			return map;
		}
		map.put("type", "success");
		map.put("msg", "删除成功");
		return map;
	}
	
	@PostMapping("/get_list")
	@ResponseBody
	public Map<String, Object> getList(
			@RequestParam(value = "name", required = false, defaultValue = "")String name,
			Page page
			) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("name", "%" + name + "%");
		query.put("offset", page.getOffset());
		query.put("pageSize", page.getRows());
		map.put("rows", service.findList(query));
		map.put("total", service.getTotal("%" + name + "%"));
		return map;
	}
	
	@ResponseBody
	@PostMapping("/add")
	public Map<String, String> add(Grade grade){
		Map<String, String> map = new HashMap<String, String>();
		map.put("type", "error");
		if(StringUtil.isEmpty(grade.getName())) {
			map.put("msg", "年级名次不能为空");
			return map;
		}
		if(service.add(grade) <= 0) {
			map.put("msg", "添加失败");
			return map;
		}
		
		map.put("type", "success");
		map.put("msg", "添加成功");
		return map;
	}
	
}
